package fr.perso.ppo.springintegration.business;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3.schools.ws.TempConvertConnector;

import com.exception.ws.BusinessException;
import com.exception.ws.TechnicalException;
import com.google.common.base.Preconditions;

import fr.perso.ppo.springintegration.domain.PaiementGDPA;

@Component("tigreWsService")
public class TigreWsServiceImpl implements InitializingBean, TigreWsService{
	
	private Logger log = LoggerFactory.getLogger(TigreWsServiceImpl.class);
	private static Logger logWs = LoggerFactory.getLogger("logWs");
	
	@Autowired
	private TempConvertConnector connector;
	
	
	public void afterPropertiesSet() throws Exception {
		Preconditions.checkNotNull(connector, "the connector to WS should not be null");
		
	}
	
	
	
	/**{@inheritDoc}
	 * 
	 * @see fr.perso.ppo.springintegration.business.TigreWsService#service(fr.perso.ppo.springintegration.domain.PaiementGDPA)
	 */
	public PaiementIntegrationMessage service(PaiementGDPA paiement) throws Exception{

		String response = null;
		PaiementIntegrationMessage msg = new PaiementIntegrationMessage();
		//TODO rajouter un logger dedie aux appels SOAP (format a definir) => supervision
		long startDate = System.currentTimeMillis();

		try {
			log.info("=====================>call ws outside for {}",paiement.getCDENC());
			
			log.info("=====================> fin call ws ws outside for {} in {} ms",paiement.getCDENC(),System.currentTimeMillis()-startDate);
			response = connector.celsiusToFahrenheit(paiement.getCDENC());
			parseResponse(response);
			msg.setStatut("OK");	
		} catch (TechnicalException e) {
			log.error("Erreur lors de appel WS ",e);
			msg.setStatut("Technical KO");
			//TODO should try n times (n=3) with a delay that gets bigger each time
			//see Spring batch + Spring integration
			throw e;
		} catch (BusinessException e) {
			log.warn("Erreur fonctionnelle los de appel WS",e);
			//TODO ajout de log4j extra pour limiter le fichier de log applicative a la root cause => pas de stacktrace dans ce cas.
			msg.setStatut("Business KO");
		} finally {
			long durationInMillis = System.currentTimeMillis() - startDate;
			log.info("Tigre temp convert ws (celsiusToFahrenheit)  invocation duration {} ms", durationInMillis);
			logWs.info("RCE celsiusToFahrenheit ws; {};{}", (new Object[] { msg.getStatut(), durationInMillis }));
		}

		msg.setResponse(response);
		msg.setPaiementId(String.valueOf(paiement.getId()));
		msg.setTrackingDate(new Date());

		return msg;
	}



	private void parseResponse(String response) throws BusinessException {
		if(StringUtils.contains(response, "Error")) throw new BusinessException();
		
	}

	

}
